package cn.elead.chaos.framework.web.global.cors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.elead.chaos.framework.properties.Cross;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * SpringBoot 中实现跨域访问的方法2(推荐)
 * <p>
 * 通过 拦截器 设置通用的响应头<br>
 * 
 * @author luopeng
 *
 */
@Deprecated
public class CrossInterceptor extends HandlerInterceptorAdapter {

	private Cross cross;
	
	// (yaml配置方式)
	public Cross setCross(Cross cross) {
		if (ObjectUtil.isNotNull(cross)) {
			this.cross = cross;
		} else {
			this.cross = new Cross();
		}
		return this.cross;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String curOrigin = request.getHeader(HttpHeaders.ORIGIN);
		if (StrUtil.isNotBlank(curOrigin)) {
			// 为空代表支持所有
			if (StrUtil.isBlank(cross.getAccessControlAllowOrigin())) {
				// 允许的域名白名单，可以*
				response.addHeader("Access-Control-Allow-Origin", curOrigin);
			} else {
				String[] allowUrls = StrUtil.split(cross.getAccessControlAllowOrigin(), StrUtil.COMMA);
				for (String origin : allowUrls) {
					if (origin.equals(curOrigin)) {
						response.addHeader("Access-Control-Allow-Origin", origin);
					}
				}
			}
		}else {
			String[] allowUrls = StrUtil.split(cross.getAccessControlAllowOrigin(), StrUtil.COMMA);
			for (String origin : allowUrls) {
				response.addHeader("Access-Control-Allow-Origin", origin);
			}
		}
		// 是否允许携带cookie
		response.setHeader("Access-Control-Allow-Credentials", cross.getAccessControlAllowCredentials());
		// 允许哪些类型请求，可以*
		response.setHeader("Access-Control-Allow-Methods", cross.getAccessControlAllowMethods());
		// 自定义请求头
		response.setHeader("Access-Control-Allow-Headers", cross.getAccessControlAllowHeaders());
		// 用来指定本次预检请求的有效期，单位为秒
		response.setHeader("Access-Control-Max-Age", cross.getAccessControlMaxAge());
		
		return super.preHandle(request, response, handler);
	}

}
